package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.spzx.common.core.utils.bean.BeanUtils;
import com.spzx.product.api.domain.SkuLockVo;
import com.spzx.product.domain.SkuStock;
import com.spzx.product.domain.vo.SkuStockVo;
import com.spzx.product.mapper.SkuStockMapper;
import com.spzx.product.service.ISkuStockService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品sku库存表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2024-12-19
 */
@Service
public class SkuStockServiceImpl extends ServiceImpl<SkuStockMapper, SkuStock> implements ISkuStockService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    // TODO 获取商品库存
    public SkuStockVo getSkuStock(Long skuId) {
        LambdaQueryWrapper<SkuStock> queryWrapper = new LambdaQueryWrapper<SkuStock>()
                .eq(SkuStock::getSkuId, skuId)
                .select(SkuStock::getAvailableNum, SkuStock::getSaleNum);
        SkuStock skuStock = baseMapper.selectOne(queryWrapper);
        SkuStockVo skuStockVo = new SkuStockVo();
        BeanUtils.copyProperties(skuStock, skuStockVo);
        skuStockVo.setSkuId(skuId);
        return skuStockVo;
    }

    @Override
    //TODO 检查与锁定商品库存
    @Transactional(rollbackFor = Exception.class)
    public String checkAndLock(String orderNo, List<SkuLockVo> skuLockVoList) {
        skuLockVoList.forEach(skuLockVo -> {
            SkuStock skuStock = baseMapper.check(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
            skuLockVo.setHaveStock(skuStock != null);
        });
        if (skuLockVoList.stream().anyMatch(skuLockVo -> !skuLockVo.isHaveStock())) {
            // 过滤出所有库存不足的商品
            List<SkuLockVo> noStockList = skuLockVoList.stream()
                    .filter(skuLockVo -> !skuLockVo.isHaveStock())
//                    .filter(skuLockVo -> skuLockVo.getHaveStock() ==false)
                    .collect(Collectors.toList());
            StringBuffer errorMsg = new StringBuffer();
            noStockList.forEach(noStock -> {
                Integer availableNum = baseMapper.selectById(noStock.getSkuId()).getAvailableNum();
                errorMsg
                        .append(noStock.getSkuName())
                        .append("库存不足，剩余库存：")
                        .append(availableNum)
                        .append("；");
            });
            //返回错误信息
            return errorMsg.toString();
        } else {
            for (SkuLockVo skuLockVo : skuLockVoList) {
                baseMapper.lock(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
            }
        }
        // 如果所有商品都锁定成功的情况下，需要缓存锁定信息到redis。以方便将来解锁库存 或者 减库存
        String dataKey = "sku:lock:data:" + orderNo;
        this.redisTemplate.opsForValue().set(dataKey, skuLockVoList);
        return "";
    }

    //TODO 解锁商品库存
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void unlock(String orderNo) {
        //幂等性处理
        String key = "sku:unlock:" + orderNo;
        Boolean isFirst = redisTemplate.opsForValue().setIfAbsent(key, orderNo, 1, TimeUnit.HOURS);
        if (Boolean.TRUE.equals(isFirst)) {
            // 获取锁定库存的缓存信息
            String dataKey = "sku:lock:data:" + orderNo;
            List<SkuLockVo> skuLockVoList = (List<SkuLockVo>) redisTemplate.opsForValue().get(dataKey);
            if (!CollectionUtils.isEmpty(skuLockVoList)) {
                // 解锁库存
                skuLockVoList.forEach(skuLockVo ->
                        baseMapper.unlock(skuLockVo.getSkuId(), skuLockVo.getSkuNum()));
            }
            // 解锁库存之后，删除锁定库存的缓存
            redisTemplate.delete(dataKey);
        }
    }

    //TODO 扣减商品库存
    @Override
    public void minus(String orderNo) {
        //幂等性处理
        String key = "sku:minus:" + orderNo;
        //业务去重，防止重复消费
        Boolean isExist = redisTemplate.opsForValue().setIfAbsent
                (key, orderNo, 1, TimeUnit.HOURS);
        if(Boolean.TRUE.equals(isExist)){
            String dataKey = "sku:lock:data:" + orderNo;
            List<SkuLockVo> skuLockVoList = (List<SkuLockVo>)redisTemplate.opsForValue().get(dataKey);
            if (!CollectionUtils.isEmpty(skuLockVoList)){
                // 减库存
                skuLockVoList.forEach(skuLockVo -> {
                    int row = baseMapper.minus(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
                });
                // 扣减库存之后，删除锁定库存的缓存。
                redisTemplate.delete(dataKey);
            }
        }
    }
}
